<template>
  <div class="main">
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品列表</el-breadcrumb-item>
      <el-breadcrumb-item>添加商品</el-breadcrumb-item>
    </el-breadcrumb>

    <el-card>
      <el-alert
        title="添加商品信息"
        type="info"
        center
        show-icon
        :closable="false"
      >
      </el-alert>

      <el-steps :space="250" :active="activeIndex * 1" finish-status="success" align-center>
        <el-step title="基本信息">基本信息</el-step>
        <el-step title="商品参数">商品参数</el-step>
        <el-step title="商品属性">商品属性</el-step>
        <el-step title="商品图片">商品图片</el-step>
        <el-step title="商品内容">商品内容</el-step>
        <el-step title="完成">完成</el-step>
      </el-steps>

      <el-form
        :model="addGoodsForm"
        ref="addGoodsFormRef"
        :rules="addGoodsFormRules"
        label-position="top"
      >
        <el-tabs
          v-model="activeIndex"
          tab-position="left"
          :before-leave="beforeTabLeave"
          @tab-click="tabClicked"
        >
          <el-tab-pane name="0" label="基本信息">
            <el-form-item label="商品名称：" prop="goods_name">
              <el-input v-model="addGoodsForm.goods_name"></el-input>
            </el-form-item>
            <el-form-item label="商品价格：" prop="goods_price">
              <el-input v-model="addGoodsForm.goods_price" type="number" @keyup.native="proving($event)"></el-input>
            </el-form-item>
            <el-form-item label="商品重量：" prop="goods_weight">
              <el-input v-model="addGoodsForm.goods_weight" type="number" @keyup.native="proving($event)"></el-input>
            </el-form-item>
            <el-form-item label="商品数量：" prop="goods_number">
              <el-input v-model="addGoodsForm.goods_number" type="number" @keyup.native="proving($event)"></el-input>
            </el-form-item>
            <el-form-item label="商品分类：" prop="goods_cat">
              <el-cascader
                v-model="addGoodsForm.goods_cat"
                :options="cateOptions"
                @change="handlerCascaderChange"
                :props="cateOptionProps"
                clearable
                expand-trigger="hover"
              >
              </el-cascader>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane name="1" label="商品参数">
            <el-form-item
              :label="item.attr_name"
              v-for="item in manyTableData"
              :key="item.attr_id"
            >
              <el-checkbox-group v-model="item.attr_vals">
                <el-checkbox :label="cb" v-for="(cb,i) in item.attr_vals" :key="i" border size="mini"></el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane name="2" label="商品属性">
            <el-form-item :label="item.attr_name" v-for="item in onlyTableData" :key="item.attr_id">
              <el-input v-model="item.attr_val"></el-input>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane name="3" label="商品图片">
            <el-upload
              class="upload-demo"
              :action="uploadUrl"
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              accept="image/*"
              list-type="picture"
              :headers="headerObj"
              :on-success="handleSuccess"
            >
              <el-button size="small" type="primary">点击上传</el-button>
            </el-upload>
          </el-tab-pane>
          <el-tab-pane name="4" label="商品内容">
            <quill-editor v-model="addGoodsForm.goods_introduce"></quill-editor>
            <el-button type="primary" @click="addGoods">添加商品</el-button>
          </el-tab-pane>
        </el-tabs>
      </el-form>
    </el-card>

    <!--预览图片弹窗-->
    <el-dialog
      title="图片预览"
      :visible.sync="previewDialogVisible"
      width="50%"
      :close-on-click-modal="false"
    >
      <img :src="previewPath" class="previewImg">
    </el-dialog>
  </div>
</template>

<script>

import { getParamsData } from '@/api/goods/params'
import { getCateList } from '@/api/goods/cate'
import _ from 'lodash'
import { addGoods } from '../../../api/goods/list'
export default {
  name: 'AddGoods',
  data: () => {
    return {
      addGoodsForm: {
        goods_name: '',
        goods_price: null,
        goods_weight: null,
        goods_number: null,
        goods_cat: [],
        pics: [],
        goods_introduce: '',
        attrs: []
      },
      addGoodsFormRules: {
        goods_name: [{ required: true, message: '请填写商品名称', trigger: 'blur' }],
        goods_price: [{ required: true, message: '请填写商品价格', trigger: 'blur' }],
        goods_weight: [{ required: true, message: '请填写商品重量', trigger: 'blur' }],
        goods_number: [{ required: true, message: '请填写商品数量', trigger: 'blur' }],
        goods_cat: [{ required: true, message: '请选择商品分类', trigger: 'blur' }]
      },
      cateOptions: [],
      cateOptionProps: {
        value: 'cat_id',
        label: 'cat_name'
      },
      activeIndex: '0',
      currentSelectedCateId: 0,
      manyTableData: [],
      onlyTableData: [],
      uploadUrl: 'http://127.0.0.1:8888/api/private/v1/upload',
      headerObj: {
        Authorization: window.sessionStorage.getItem('token')
      },
      previewPath: '',
      previewDialogVisible: false,
      activeObj: {
        params: false,
        attrs: false
      }
    }
  },
  created () {
    this.getCateList()
  },

  methods: {

    // 添加商品
    addGoods () {
      if (!this.activeObj.params) return this.$message.error('请选择商品参数')
      if (!this.activeObj.attrs) return this.$message.error('请填写商品属性')
      this.$refs.addGoodsFormRef.validate(async valid => {
        if (!valid) return this.$message.error('请填写必要的基本信息！')
        // 深拷贝对象
        // const form = JSON.parse(JSON.stringify(this.addGoodsForm))
        const form = _.cloneDeep(this.addGoodsForm)
        form.goods_cat = form.goods_cat.join(',')

        // 处理动态参数
        this.manyTableData.forEach(item => {
          const newInfo = {
            attr_id: item.attr_id,
            attr_value: item.attr_vals.join(' ')
          }
          this.addGoodsForm.attrs.push(newInfo)
        })
        // 处理静态属性
        this.onlyTableData.forEach(item => {
          const newInfo = {
            attr_id: item.attr_id,
            attr_value: item.attr_vals.join(' ')
          }
          this.addGoodsForm.attrs.push(newInfo)
        })
        form.attrs = this.addGoodsForm.attrs
        // console.log(form)
        const { data: res } = await addGoods(form)
        if (res.meta.status !== 201) return this.$message.error(res.meta.msg)
        this.$message.success(res.meta.msg)
        await this.$router.push('/goods')
      })
    },

    // 图片上传成功后的操作
    handleSuccess (res) {
      const picInfo = { pic: res.data.tmp_path }
      this.addGoodsForm.pics.push(picInfo)
    },

    // 预览图片
    handlePreview (file) {
      this.previewPath = file.response.data.url
      this.previewDialogVisible = true
    },

    // 删除图片
    handleRemove (file) {
      const filePath = file.response.data.tmp_path
      const i = this.addGoodsForm.pics.findIndex(x => x.pic === filePath)
      this.addGoodsForm.pics.splice(i, 1)
    },

    // 监听商品价格、重量、数量键盘抬起事件
    proving (e) {
      if (e.target.value < 0) {
        e.target.value = null
      }
    },

    // 选中某个tab标签页
    async tabClicked () {
      // 证明选中的是动态参数面板
      if (this.activeIndex === '1') {
        const { data: res } = await getParamsData(this.currentSelectedCateId, 'many')
        if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
        res.data.map(item => {
          item.attr_vals = item.attr_vals ? item.attr_vals.split(' ') : []
        })
        this.manyTableData = res.data
      }

      // 证明选中的是静态属性面板
      if (this.activeIndex === '2') {
        const { data: res } = await getParamsData(this.currentSelectedCateId, 'only')
        if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
        res.data.map(item => {
          item.attr_vals = item.attr_vals ? item.attr_vals.split(' ') : []
        })
        this.onlyTableData = res.data
      }
    },

    // tab标签页离开之前
    beforeTabLeave (activeName, oldActiveName) {
      if (oldActiveName === '0' && this.addGoodsForm.goods_cat.length !== 3) {
        this.$message.error('请先选择商品分类！')
        return false
      }
      if (activeName === '1') this.activeObj.params = true
      if (activeName === '2') this.activeObj.attrs = true
      return true
    },

    // 获取分类数据
    async getCateList () {
      const { data: res } = await getCateList({ pagenum: 1, pagesize: 99999999 })
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.cateOptions = res.data.result
    },

    // 处理级联选择框发生改变
    handlerCascaderChange () {
      if (this.addGoodsForm.goods_cat.length !== 3) {
        this.addGoodsForm.goods_cat = []
        return
      }
      this.currentSelectedCateId = this.addGoodsForm.goods_cat[2]
    }
  }
}
</script>
<style lang="less" scoped>
  @import "./index";
</style>
